package com.jsmtr.rms.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class PhoneTools {

    public static boolean sendMsg2(String tel, String cont,String username,String password,String host) {
        try {
            StringBuffer sendURL = new StringBuffer();
            sendURL.append("http://192.168.1.34:8082/MWGate/wmgw.asmx/MongateCsSpSendSmsNew");
            //sendURL.append("?userid=DBSMS1");
            //sendURL.append("&password=123456");
            sendURL.append("?userid=zpxt");
            sendURL.append("&password=zpdx68002110");
            URL url = new URL(sendURL.toString());    //把字符串转换为URL请求地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();// 打开连接
            //addRequestProperty添加相同的key不会覆盖，如果相同，内容会以{name1,name2}
            connection.addRequestProperty("from", "zpxt");  //来源哪个系统
            //setRequestProperty添加相同的key会覆盖value信息
            //setRequestProperty方法，如果key存在，则覆盖；不存在，直接添加。
            //addRequestProperty方法，不管key存在不存在，直接添加。
            connection.setRequestProperty("user", "user");  //访问申请用户
            InetAddress address = InetAddress.getLocalHost();
            String ip=address.getHostAddress();//获得本机IP
            connection.setRequestProperty("ip",ip);  //请求来源IP
            connection.setRequestProperty("port", "8082");
            connection.connect();// 连接会话
            // 获取输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {// 循环读取流
                sb.append(line);
            }
            br.close();// 关闭流
            connection.disconnect();// 断开连接
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("失败!");
        }
        return true;
    }


    public static boolean sendMsg(String tel, String cont,String username,String password,String host) {
        // 创建Httpclient对象
        HttpHost proxy = new HttpHost("172.17.210.11", 8082);
        //DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
       /* CloseableHttpClient httpclient = HttpClients.custom()
                .setProxy(proxy)
                .build();*/


        String resultString = "";
        CloseableHttpResponse response = null;
        CloseableHttpClient httpclient=null;
        httpclient = HttpClients.createDefault();
        try {
            // 创建uri
            StringBuffer sendURL = new StringBuffer();
            //sendURL.append("http://192.168.1.34:8082/MWGate/wmgw.asmx/MongateCsSpSendSmsNew");
            //sendURL.append("?userid=DBSMS1");
            //sendURL.append("&password=123456");
            //sendURL.append("?userid=zpxt");
            //sendURL.append("&password=zpdx68002110");
            sendURL.append(host);
            sendURL.append("?userid="+username);
            sendURL.append("&password="+password);
            sendURL.append("&pszMobis=");
            sendURL.append(tel);
            sendURL.append("&pszMsg=");
            sendURL.append(URLEncoder.encode(cont, "utf-8"));
            sendURL.append("&iMobiCount=1&pszSubPort=*");

            // 创建http GET请求
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(8000)
                    .setConnectTimeout(8000)
                    .setProxy(proxy)
                    .build();
            //String testurl="http://127.0.0.1:5555";
            //HttpGet httpGet = new HttpGet(testurl);
            HttpGet httpGet = new HttpGet(sendURL.toString());
            httpGet.setHeader("Connection", "Close");
            httpGet.setConfig(requestConfig);
           // httpGet.setConfig();
            // 执行请求
            response = httpclient.execute(httpGet);
            // 判断返回状态是否为200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println("短信发送结果:"+resultString);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return  false;
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpclient!=null) {
                    httpclient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /*public static boolean sendMsg_bak(String tel, String cont,String username,String password,String host) {
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = null;
        String result=null;
        try {
            //RestTemplate restTemplate=new RestTemplate();
            StringBuffer sendURL = new StringBuffer();
            //sendURL.append("http://192.168.1.34:8082/MWGate/wmgw.asmx/MongateCsSpSendSmsNew");
            //sendURL.append("?userid=DBSMS1");
            //sendURL.append("&password=123456");
            //sendURL.append("?userid=zpxt");
            //sendURL.append("&password=zpdx68002110");
            sendURL.append(host);
            sendURL.append("?userid="+username);
            sendURL.append("&password="+password);
            sendURL.append("&pszMobis=");
            sendURL.append(tel);
            sendURL.append("&pszMsg=");
            sendURL.append(URLEncoder.encode(cont, "utf-8"));
            sendURL.append("&iMobiCount=1&pszSubPort=*");

            httpClient.getHostConfiguration().setHost(  "172.17.10.21" , 80, "http"  );
            getMethod = new GetMethod(sendURL.toString());
            getMethod.setRequestHeader("Connection", "close");
            httpClient.executeMethod(getMethod);

            //result=   restTemplate.getForObject(sendURL.toString(), String.class);
            //System.out.println(result);
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            if (null != result){
                getMethod.releaseConnection();
            }

        }

    }*/

    public static boolean sendMsg(List<Map<String, String>> msgs,String username,String password,String host) {
        try {
            for (Map<String, String> map : msgs) {
                sendMsg(map.get("tel"), map.get("cont"),username,password,host);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }


    public static Map sendMsgByList(List<Map<String, String>> msgs,String username,String password,String host) {
        Map resultMap=new HashMap();
        resultMap.put("totalNum",msgs.size());
        try {
            Integer successNum=0;
            Integer errorNum=0;
            for (Map<String, String> map : msgs) {
              boolean sendResult=  sendMsg(map.get("tel"), map.get("cont"),username,password,host);
              if (sendResult){
                  successNum++;
              }else {
                  errorNum++;
              }
            }

            resultMap.put("successNum",successNum);
            resultMap.put("errorNum",errorNum);
            resultMap.put("errmessage",null);
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("errmessage","短信发送失败");
        }
        return  resultMap;
    }
}